//防抖 每隔一段固定的时间，才做一次任务
export function throttle(callback, time) {
  //初始时间
  var startTime = (new Date()).valueOf()
  return function () {
    var nowTime = (new Date()).valueOf()
    var duration = nowTime - startTime;
    var arg = Array.prototype.slice.call(arguments)
    //超时触发
    if(duration >= time) {
      callback.apply(this, arg)
      startTime = nowTime
    }
  }
}

//节流 '最后一辆末班车', 在一定时间内等待，只有最后一个任务是，才做
export function antiShake(callback, time) {
  //初始时间
  var startTime = (new Date()).valueOf()
  var timer = null;
  return function () {
    var nowTime = (new Date()).valueOf()
    var duration = nowTime - startTime;
    var arg = [].slice(arguments, 0)
    var context = this
    //时间未到
    if (duration < time) {
      if (timer) clearTimeout(timer)
      //设置定时器
      timer = setTimeout(function () {
        callback.apply(context, arg)
      }, time)
    }
    //重新计时
    startTime = nowTime
  }
}


export function passive(callback, lTime, rTime) {
  try {
    if(lTime > rTime) throw new Error('lTime should bigger then rTime')
  } catch(e) {
    alert(e)
    return null
  }
  //初始时间
  var startTime = (new Date()).valueOf()
  var timer = null
  var times = 0
  return function () {
    var nowTime = (new Date()).valueOf()
    var duration = nowTime - startTime;
    var arg = Array.prototype.slice.call(arguments)
    var context = this
    //时间未到
    if (duration < lTime) {
      if (timer) clearTimeout(timer)
      //设置定时器
      timer = setTimeout(function () {
        callback.apply(context, arg)
      }, rTime)
    } else {
      //重新计时
      startTime = nowTime
      callback.apply(this, arg)
      times++;
      console.log(times)
    }
  }
}
